<?php

/*
Plugin Name: Synergy User Profile
Plugin URL: http://www.synergy.com/
Description: Synergy user profile wordpress plugin for Synergy Resource management system.
Version: 1.0
Author: Weranga Kaluarachchi
Author URI: http://www.synergy.com
License: GPL
*/


// import javascript file into syn_user_profile plugin
wp_enqueue_script('syn_user_profile_script', '/wp-content/plugins/syn_user_profile/syn_user_profile.js');

$isSetViewState = false;

/**
 * Main method of the syn_user_profile plugin
 */
function widget_syn_user_profile() {
	global $wpdb;
	global $current_user;
	global $is_iphone;
	
	echo $before_widget; 
	if(isset($_POST[btnSynProfileUpdate]) || $_POST[btnSynProfileUpdate] == "UpdateUser") {
			if(isset($_POST[hdUserID])) {
				update_user_profile($_POST[hdUserID]);
				echo "<script type='text/javascript'>";
				echo "alert('Your profile has been successfully updated.');";
				echo "</script>";
			}
			else {
				echo "<script type='text/javascript'>";
				echo "alert('System can not perform this action right now, try later!');";
				echo "</script>";
			}			
			
	}
	else if(isset($_POST[btnChangePassword]) || $_POST[btnChangePassword] == "updatePassword") {
		if(validate_old_password($current_user->ID, $_POST[txtSynOldUserPassword])) {
			update_password($current_user->ID, $_POST[txtSynOldUserPassword]);
			echo "<script type='text/javascript'>";
			echo "alert('Password has been successfully updated.');";
			echo "</script>";
			$isSetViewState = false;
			//header(wp_logout_url());			
		}
		else {
			echo "<script type='text/javascript'>";
			echo "alert('Old password is incorrect!');";
			echo "</script>";			
			$isSetViewState = true;			
		}
	}

	echo "<h4>Edit Profile</h4><br/>";
	echo "<div class='synForm'>\n";
	echo "<form name='frmSynSearch' method='post' action='$PHP_SELF'>";
	if ($is_iphone) echo '<div class="synleft">';
	foreach (get_user_profile($current_user->ID) as $userRow) {
		echo "<input type='hidden' name='hdUserID' value='$userRow->ID'/>\n";
		echo "<p><label for='username'><strong>Username:</strong></label><br /><input type='text' name='txtSynProfileFirstName' disabled='disabled' value='$userRow->user_login'/></p>\n";
		echo "<p><label for='firstname'><strong>First Name:</strong></label><br /><input type='text' id='txtSynProfileFirstName' maxlength='50' name='txtSynProfileFirstName' value='$userRow->first_name'/></p>\n";
		echo "<p><label for='lastname'><strong>Last Name:</strong></label><br /><input type='text' name='txtSynProfileLastName' maxlength='50' value='$userRow->last_name'/></p>\n";

		if ($is_iphone) echo '</div><div class="synright">';
		echo "<p><b>Contact Info</b><br />\n";
		echo "<p><label for='emailaddress'><strong>Email:</strong></label><br /><input type='text' id='txtSynProfileEmail' maxlength='70' name='txtSynProfileEmail' value='$userRow->user_email'/></p>\n";
		echo "<p><label for='phonenumber'><strong>Phone:</strong></label><br /><input type='text' id='txtSynProfilePhone' maxlength='15' name='txtSynProfilePhone' value='$userRow->user_url'/></p>\n";
		echo "<p><button type='submit' id='btnSynProfileUpdate' name='btnSynProfileUpdate' value='updateUser' onclick='return validateInputs();'>Update Profile</button></p>\n";
		
		echo "<br />\n";
		echo '<span onclick="toggleChangePassword(\'changepassword\', this);" style="cursor:pointer">[Change Password >>]</span><br />';
				
		if($isSetViewState){
			echo '<div id="changepassword" style="display:inline;">' . "\n";
		}
		else{
			echo '<div id="changepassword" style="display:none;">' . "\n";
		}
		
		echo "<label id='lblErrPassword' style='color: red'></label><br />";
		echo "<label for='oldpassword'><strong>Old Password:</strong></label><br /><input type='password' maxlength='50' id='txtSynOldUserPassword' name='txtSynOldUserPassword' value=''/><br />\n";
		echo "<script type='text/javascript'>document.getElementById('txtSynOldUserPassword').focus(); </script><br />\n";
		echo "<label for='newpassword'><strong>New Password:</strong></label><br /><input type='password' maxlength='50' name='txtSynNewUserPassword' id='txtSynNewUserPassword'/><br />\n";
		echo "<label for='confirmpassword'><strong>Confirm Password:</strong></label><br /><input type='password' maxlength='50' name='txtSynUserConfirmPassword' id='txtSynUserConfirmPassword'/><br />\n";
		echo "<button type='submit' id='btnChangePassword' name='btnChangePassword' value='updatePassword' onclick='return matchNewPassword();'>Save</button><br />\n";
		echo "</div>";
		if ($is_iphone) echo '</div>';
		echo " </form>";
		echo "</div> <!-- end class=synform -->";

	}	
	echo $after_widget; 
	
}


/**
 * Get profile of the current user
 * @param	int	user ID
 */
function get_user_profile($userID) {	
	global $wpdb;
	global $current_user;	
	$userTable = $wpdb->prefix."users";
	$userMetaTable = $wpdb->prefix."usermeta";
	$myrows = $wpdb->get_results("SELECT a.ID, a.user_login, a.user_url, a.user_email, a.display_name, 
	b.meta_value as first_name, c.meta_value as last_name FROM $userTable as a, $userMetaTable as b, 
	$userMetaTable as c WHERE a.ID = $userID AND a.ID = b.user_id AND a.ID = c.user_ID AND b.meta_key = 'first_name' AND c.meta_key = 'last_name'");	
	return $myrows;
	
	
}


/**
 * Update the profile of the current user
 * @param	int	user ID
 */
function update_user_profile($userID) {
	global $wpdb;
	global $current_user;
	$userTable = $wpdb->prefix."users";
	$userMetaTable = $wpdb->prefix."usermeta";
	$updateUserSchema = "UPDATE $userTable SET user_email='".cleanUserInput($_POST[txtSynProfileEmail])."', user_url='".cleanUserInput($_POST[txtSynProfilePhone])."', display_name='".cleanUserInput($_POST[txtSynProfileDisplayName])."' 
						WHERE ID = $userID";
	$wpdb->query($updateUserSchema);
	$updateMetaSchema1 = "UPDATE $userMetaTable SET meta_value='".cleanUserInput($_POST[txtSynProfileFirstName])."' WHERE meta_key = 'first_name' AND user_id = $userID"; 
	$wpdb->query($updateMetaSchema1);
	$updateMetaSchema2 = "UPDATE $userMetaTable SET meta_value='".cleanUserInput($_POST[txtSynProfileLastName])."' WHERE meta_key = 'last_name' AND user_id = $userID"; 
	$wpdb->query($updateMetaSchema2);
}



/**
 * Validate old password of the current user
 * @param	int	user ID
 * @param	string old password
 */
function validate_old_password($userID, $password) {
	global $wpdb;
	$userName = ""; 
	$userTable = $wpdb->prefix."users";
	
	$myrows = $wpdb->get_results("SELECT user_login FROM $userTable WHERE ID = $userID AND user_status = 0");
	foreach ($myrows as $myrow) {
		$userName = $myrow->user_login;		
	}
	if(user_pass_ok($userName, $password)) {
		return true;
	}
	return false;		
}


/**
 * Sanitize Database Inputs
 * @param	string	input applying sanitize
 */
function cleanUserInput($input) {
  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );

    $output = preg_replace($search, '', $input);
    return $output;
  }
  

/**
 * Change the password of the current user
 * @param	int	user ID
 * @param	string new password
 */
function update_password($userID, $password) {
	global $wpdb;
	global $current_user;
	$userTable = $wpdb->prefix."users";
	$encPassword = wp_hash_password($_POST[txtSynNewUserPassword]);
	$updateUserSchema = "UPDATE $userTable SET user_pass = '$encPassword' 
						WHERE ID = $userID";
	$wpdb->query($updateUserSchema);	
}

// register syn_user_profile widget  
register_sidebar_widget('Synergy User Profile', 'widget_syn_user_profile');

// register plugin and install it to the wordpress
add_action('activate_syn_user_profile/syn_user_profile.php', 'widget_syn_user_profile');
?>